import { getUserInfo, login, getUserDetailById } from '@/api/user'
import { resetRouter } from '@/router'
import { setToken, getToken, removeToken } from '@/utils/auth'

const state = {
  token: getToken() || '',
  // token: localStorage.getItem('token') || ''
  userInfo: {}
}
const mutations = {
  setToken(state, data) {
    setToken(data)
    // localStorage.setItem('token', data)
    state.token = data
  },
  // 设置用户信息
  setUserInfo(state, data) {
    state.userInfo = { ...data } // 用浅拷贝去赋值对象,因为这样数据更新后才会触发组件的更新
  },
  // 定义删除token的mutations方法
  removeToken(state) {
    removeToken()
    state.token = ''
  },

  // 删除用户信息
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  async login(store, data) {
    const res = await login(data)
    console.log('action接受的res', res) // 登录时先经过拦截器,此时拦截器返回data
    store.commit('setToken', res)
    // token主动失效,先在登录actions时记录时间保存在本地存储
    localStorage.setItem('loginTime', Date.now())
  },

  async getUserInfo(store) {
    const res = await getUserInfo()
    const userDetail = await getUserDetailById(res.userId)
    // 将两个接口返回的结果拼接在一起
    const result = { ...res, ...userDetail }
    // 调用mutations
    store.commit('setUserInfo', result)
    console.log('用户数据', result)
    return result
  },

  logout(store) {
    store.commit('removeToken')
    store.commit('removeUserInfo')
    // 重置路由,从router/index引入的重置路由函数
    resetRouter()
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

